package com.sat.client.fragment

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.activity.OnBackPressedCallback
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.liulishuo.filedownloader.BaseDownloadTask
import com.liulishuo.filedownloader.FileDownloadListener
import com.liulishuo.filedownloader.FileDownloader
import com.sat.client.R
import com.sat.client.VideoActivity
import com.sat.client.adapter.DirectoryAdapter
import com.sat.client.adapter.FileItemAdapter
import com.sat.client.app.GlobalData
import com.sat.client.databinding.FragmentFilesBinding
import com.sat.client.utils.FileDownloaderHelper
import com.sat.client.utils.FileType
import com.sat.client.vm.FilesFragmentVM
import com.sat.common.base.BaseFragment
import net.mikaelzero.mojito.Mojito
import net.mikaelzero.mojito.impl.DefaultPercentProgress
import net.mikaelzero.mojito.impl.NumIndicator

/**
 * A simple [Fragment] subclass.
 * Use the [FilesFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class FilesFragment : BaseFragment<FilesFragmentVM, FragmentFilesBinding>() {
    private val directoryAdapter by lazy {
        DirectoryAdapter()
    }

    private val fileItemAdapter by lazy {
        FileItemAdapter()
    }

    override fun layoutId(): Int {

        return R.layout.fragment_files
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        mBinding?.run {
            rvDirs.run {
                layoutManager =
                    LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
                adapter = directoryAdapter
                directoryAdapter.setOnItemClickListener { itmes, _, positon ->
                    try {
                        val stringBuilder = StringBuilder()
                        for (i in 0..positon) {
                            if (i == 0) {
                                stringBuilder.append(itmes.items[i])
                            } else {
                                stringBuilder.append("/" + itmes.items[i])
                            }

                        }
                        viewModel.changeDir(stringBuilder.toString().trimEnd())
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }


                }
            }
            rvList.run {
                layoutManager = GridLayoutManager(requireContext(), 3)
                adapter = fileItemAdapter
                fileItemAdapter.setOnItemClickListener { itmes, _, positon ->
                    itmes.getItem(positon)?.let {
                        when (it.type) {
                            FileType.DIRECTORY -> {
                                viewModel.updateFileItem(it)
                            }

                            FileType.IMAGE -> {
                                val urls = itmes.items.filter { i ->
                                    i.type == FileType.IMAGE
                                }.map { i ->
                                    i.url ?: ""
                                }

                                Mojito.start(context) {
                                    urls(urls)
                                    progressLoader {
                                        DefaultPercentProgress()
                                    }
                                    setIndicator(NumIndicator())
                                    position(urls.indexOf(it.url))
                                }
//                                viewModel.defUI.showDialog.call()
//                                FileDownloaderHelper.downloadFile(
//                                    it.url!!,
//                                    it.name,
//                                    onError = { e ->
//                                        viewModel.defUI.dismissDialog.call()
//                                        showToast(
//                                            context.getString(
//                                                R.string.download_error,
//                                                e.message
//                                            ))
//
//
//                                    },
//                                    onComplete = {
//                                        viewModel.defUI.dismissDialog.call()
//                                        showToast(
//                                            context.getString(
//                                                R.string.download_complete,
//                                                it.name
//                                            )
//                                        )
//                                    })
                            }

                            FileType.VIDEO -> {

                                startActivity(
                                    Intent(
                                        requireContext(),
                                        VideoActivity::class.java
                                    ).apply {
                                        putExtra("url", it.url)
                                    })
                            }

                            else -> {

                            }
                        }


                    }
                }
            }
            imvBack.setOnClickListener {
                if (!viewModel.backLastDir()) {
                    // 处理返回按钮点击事件
                    requireActivity().supportFragmentManager.popBackStack()
                }
            }
            refreshLayout.setOnRefreshListener {

                refreshLayout.finishRefresh()
            }

            // 自定义返回按钮行为
            val callback = object : OnBackPressedCallback(true) {
                override fun handleOnBackPressed() {
                    if (!viewModel.backLastDir()) {
                        // 处理返回按钮点击事件
                        requireActivity().supportFragmentManager.popBackStack()
                    }
                }
            }
            requireActivity().onBackPressedDispatcher.addCallback(
                viewLifecycleOwner,
                callback
            )
        }
        viewModel.currentFileItem.observe(this) {
            directoryAdapter.submitList(it.path.split("/"))
            fileItemAdapter.submitList(it.contents)

        }
        GlobalData.fileItem?.run {
            viewModel.updateFileItem(this)
        }

    }


}